import fitz  # PyMuPDF
from PIL import Image, ImageDraw, ImageFont
import io
import os
import random
import shutil  # 新增导入

def create_text_image(text, font_path, fontsize=16, text_color=(255, 0, 0), scale=4):
    # 生成高清文字图片
    font = ImageFont.truetype(font_path, fontsize * scale)
    dummy_img = Image.new("RGB", (1, 1))
    draw = ImageDraw.Draw(dummy_img)
    bbox = draw.textbbox((0, 0), text, font=font)
    w = bbox[2] - bbox[0]
    h = bbox[3] - bbox[1]

    img = Image.new("RGBA", (w + 10 * scale, h + 10 * scale), (255, 255, 255, 0))
    draw = ImageDraw.Draw(img)
    draw.text((5 * scale, 5 * scale), text, font=font, fill=text_color + (255,))
    return img, w, h


from openpyxl import load_workbook
from openpyxl.styles import Font

def is_merged_cell(ws, row, col):
    """检查指定位置是否是合并单元格"""
    cell_str = f"{get_column_letter(col)}{row}"
    for merged_range in ws.merged_cells.ranges:
        if cell_str in merged_range:
            return True
    return False

from openpyxl.utils import get_column_letter

from openpyxl.worksheet.worksheet import Worksheet  # 添加这行

from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor

def insert_score_and_comment_with_ppt(ppt_path, output_path, score, comment):
    try:
        prs = Presentation(ppt_path)
        slide = prs.slides[0]

        left = Inches(0.3)
        top = Inches(0.2)
        width = Inches(6)
        height = Inches(1)

        textbox = slide.shapes.add_textbox(left, top, width, height)
        text_frame = textbox.text_frame
        text_frame.word_wrap = True

        p = text_frame.paragraphs[0]
        run = p.add_run()
        run.text = f"成绩：{score}\n评语：{comment}"

        font = run.font
        font.name = '微软雅黑'
        font.size = Pt(16)
        font.bold = True
        font.color.rgb = RGBColor(255, 0, 0)  # 红色

        prs.save(output_path)
        print(f"保存成功：{output_path}")
        return 1

    except Exception as e:
        print(f"处理失败：{ppt_path}，错误类型：{type(e).__name__}\nTraceback: {e}")
        return 0



def deal_one(ppt_path, output_path, comment, score):
    return insert_score_and_comment_with_ppt(
        ppt_path, output_path, score, comment
    )


import os
import random

def batch_process_ppts(
    input_dir,
    output_dir,
    good_comments,
    bad_comments,
    good_student_names,
    good_score_range=(97, 99),
    bad_score_range=(94, 96),
    unprocessed_dir=None
):
    os.makedirs(output_dir, exist_ok=True)

    if unprocessed_dir:
        os.makedirs(unprocessed_dir, exist_ok=True)

    results = []

    for filename in os.listdir(input_dir):
        if filename.endswith(".pptx"):
            ppt_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)

            student_name = filename

            if any(name in student_name for name in good_student_names):
                score = random.randint(*good_score_range)
                comment = random.choice(good_comments)
            else:
                score = random.randint(*bad_score_range)
                comment = random.choice(bad_comments)

            result_flag = deal_one(ppt_path, output_path, comment, score)

            if result_flag == 0:
                score = 0
                if unprocessed_dir:
                    shutil.copy(ppt_path, os.path.join(unprocessed_dir, filename))

            results.append((student_name, score))

    return results




# 示例用法
if __name__ == "__main__":
    input_dir = "/Users/anyi/Desktop/2/ppt作业"  # 原始PDF文件夹路径
    output_dir = "/Users/anyi/Desktop/2/2_out/ppt作业"  # 输出文件夹路径
    unprocessed_dir = "/Users/anyi/Desktop/2/2_out/ppt作业/未处理"
    comments_better = [
        (
            "PPT内容逻辑清晰，结构完整，条理分明，能够很好地展示主题核心观点。\n"
            "配图得当，排版美观，整体设计协调统一，色彩搭配合理，具有较强的视觉表达力。\n"
            "语言简练有力，配合图文形成良好表达效果，展现出优秀的资料整合与表达能力。\n"
        ),
        (
            "整体结构紧凑，主题明确，内容详实且重点突出。\n"
            "图表与示意图使用恰当，提升了PPT的表现力。\n"
            "文字精炼，表达清晰，风格统一，体现了较高的专业素养与设计水平。\n"
        ),
        (
            "PPT呈现内容丰富、分析深入，页面设计规范统一，视觉引导性强。\n"
            "有效结合图形、文字与数据，传递信息准确，逻辑性强，表达生动有感染力。\n"
            "整体体现出较强的信息组织能力与良好的审美意识。\n"
        ),
        (
            "汇报内容条理清楚，数据充分，观点鲜明且具有逻辑支撑。\n"
            "排版规范，色彩和布局设计合理，图文结合自然，视觉效果良好。\n"
            "语言表达清晰准确，整体呈现效果优秀，充分展示了严谨的制作态度与表达能力。\n"
        ),
        (
            "课件主题突出，内容详实且层次清晰，重点突出，逻辑性强。\n"
            "设计简洁大方，图表清晰美观，页面一致性高，体现较强的设计感。\n"
            "语言表达规范，配合恰当的图文展示，有效提升了内容的表现力和说服力。\n"
        )
    ]

    comments_middle = [
        (
            "PPT整体结构基本清晰，但内容组织略显松散，部分页面重点不够突出。\n"
            "图表使用相对较少，或表达力一般，页面设计较为简单。\n"
            "文字表达基本规范，但在表达逻辑与语言凝练性上仍有改进空间。\n"
        ),
        (
            "能完成PPT基本制作任务，内容覆盖较完整，但表达略显平淡。\n"
            "图文结合不够紧密，排版略显单一，页面间风格不够统一。\n"
            "语言表述基本清楚，但对重点内容的突出不够明显，需增强表达逻辑。\n"
        ),
        (
            "课件内容较为完整，但部分逻辑衔接不够流畅，页面内容层次感不足。\n"
            "图表与视觉元素运用较为保守，页面美观度与表现力有待提升。\n"
            "语言表达略显口语化，整体规范性尚可，但需加强专业性表达。\n"
        ),
        (
            "PPT完成度较好，但内容较为基础，缺乏深入分析与总结。\n"
            "页面设计略显杂乱，图文比例失衡，重点信息不够突出。\n"
            "表达内容有一定条理，但语言表述略显啰嗦，建议提高简洁性与逻辑性。\n"
        ),
        (
            "基本掌握PPT制作要点，但内容设计与排版较为粗糙。\n"
            "图表较少或未能有效支持内容表达，视觉引导性弱。\n"
            "语言规范性一般，整体表达效果平平，建议加强内容优化与视觉呈现能力。\n"
        )
    ]


    good_student_name = [
        "张三", "李四", "王五", "赵六", "孙七", "周八", "吴九",
        "郑十", "钱一", "冯二", "陈三", "褚四", "卫五",
        "蒋六", "沈七", "韩八", "杨九"
    ]

    result_list = batch_process_ppts(
        input_dir, output_dir,
        comments_better, comments_middle,
        good_student_name,
        unprocessed_dir=unprocessed_dir
    )

    for name, score in result_list:
        print(f"{name}: {score}")

    with open(os.path.join(output_dir, "score_list.csv"), "w", encoding="utf-8") as f:
        f.write("姓名,分数\n")
        for name, score in result_list:
            f.write(f"{name},{score}\n")



